<?php

namespace App\Models\V2;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class AccountsManageModel extends Model
{
    protected $connection = 'mysql_2';

    protected $fillable = ['name', 'password', 'company_code', 'company_name', 'manage_name', 'remember_token'];

    protected $table = 'admin_users';


    public function getCompanyManagerUserInfo($keywords = '')
    {
        //公司列表
        $companys  = DB::table('company')
            ->select('company_id', 'company_name', 'company_sn', 'add_date', 'vip_end_date')
            ->where(['is_delete' => 0]);
        if($keywords != '')
        {
            $companys->where(function($db) use ($keywords)
            {
                $db->where('company_name','like',"%{$keywords}%")
                    ->orWhere('company_sn','like',"%{$keywords}%");
            });
        }

        $companys = $companys->paginate(10);
        foreach($companys as $company)
        {
            //查询管理员
            $company->managers = $this->where('company_code',$company->company_sn)->get();
        }
        return $companys;
    }

    public function updateAdminUsersAndCompany(array $data)
    {
        //2.更新admin_users表【xiaonangua数据库】
        $now         = date('Y-m-d', strtotime('now'));
        $password    = $data['password'] ? $data['password'] : 123456;

        $admin_users = DB::connection('mysql_2')->table('admin_users')
            ->updateOrInsert(
                ['name' => $data['manage_account'], 'pid' => 0],
                ['company_name' => $data['company_name'], 'password' => bcrypt($password), 'manage_name' => $data['manage_name'], 'pid' => 0, 'name' => $data['manage_account'], 'company_code' => $data['company_sn'], 'created_at' => $now, 'updated_at' => $now]
            );

        $status = $admin_users;

        return $status;
    }

    public function getCompnySonAccount(int $company_code)
    {
        $data = DB::connection('mysql_2')->table('admin_users')
            ->select('name', 'manage_name')
            ->where(['company_code' => $company_code, 'pid' => 1])
            ->get();
        $data ?? [];

        return $data;
    }

    public function updateAdminUsers(array $data)
    {
        $status = DB::connection('mysql_2')->table('admin_users')
            ->where(['company_code' => $data['company_code'], 'pid' => 1])
            ->update(['manage_name' => $data['manage_name'], 'name' => $data['name'], 'password' => bcrypt($data['password'])]);

        return $status;
    }
}
